// https://segmentfault.com/a/1190000022191315

import AliOss from "ali-oss";
// interface allOssInterface {
//   region;  //  地域节点，必填
//   accessKeyId; //  用户id，必填
//   accessKeySecret; //  访问密钥，必填
//   bucket;  //  bucket名称，qjdev-pred-voices
//   path?;   //  路径，默认为""，用户长传到指定文件夹
//   secure?: Boolean;    //  指示OSS客户端使用 HTTPS:true HTTP:false
//   parallel?: number;   //  分片数量
//   partSize?: number;   //  分片大小
//   defaultName?: Boolean;   //  是否使用默认名称
//   length?: number; //  随机名称长度
// };
export class DockingOSS {
  //  ali-oss 实例
  // allOSS: any;
  // parallel: number;
  // partSize: number;
  // defaultName: Boolean;
  // path;
  // length: number;
  constructor(data) {
    let {
      region,
      accessKeyId,
      accessKeySecret,
      bucket,
      secure = true,
      parallel = 3,
      partSize = 1024 * 1024,
      defaultName = false,
      path = "",
      length = 50,
    } = data;
    this.partSize = partSize;
    this.parallel = parallel;
    this.defaultName = defaultName;
    this.path = path;
    this.length = length;
    //  实例化ali-oss
    this.allOSS = new AliOss({
      region,
      accessKeyId,
      accessKeySecret,
      bucket,
      // secure
    });
  }

  /**
   * 普通上传
   * file:文件对象
   * _fileName：固定文件名称
   */
  upload(file) {
    // debugger
    /*let fileName = _fileName || this.getFileName(file)
		const pathName = this.accessPath(fileName)
		console.log('pathName: ', pathName)*/
    // console.log(this.allOSS.put(pathName, file))
    // return this.allOSS.put(pathName, file)
    // return this.allOSS.put(pathName + '/' + file.name, file)
    return this.allOSS.put(file.name, file);
  }
  /**
   * 分片上传
   * file:文件对象
   * _fileName：固定文件名称
   * progress：分片上传进度回调函数
   */
  multipartUpload(file, progress, _fileName) {
    const { parallel, partSize } = this;
    let fileName = _fileName;
    !fileName && (fileName = this.getFileName(file));
    const pathName = this.accessPath(fileName);
    return this.allOSS.multipartUpload(pathName, file, {
      parallel,
      partSize,
      progress, //获取进度条  (e, checkpoint)=>{}
    });
  }

  // 下载文件
  downLoadFile(file) {
    return this.allOSS.signatureUrl(file, {
      response: {
        "content-disposition":
          'attachment; filename="' + file,
      },
    });
  }

  //  上传进度
  //  checkpoint：返回的文件对象
  //  如果文件太小，小于分片大小的话，则不会checkpoint，为undefined
  //  说明文件直接上传成功了
  // onMultipartUploadProgress(e, checkpoint) {
  //   Reflect.set(this.checkpoints, checkpoint.uploadId, checkpoint);
  //   this.percentage = Number((e * 100).toFixed(0));
  //   if (e === 1) {
  //     Reflect.deleteProperty(this.checkpoints, checkpoint.uploadId);
  //   }
  // }
  //  中止上传
  cancel() {
    this.allOSS.cancel();
  }

  // interface checkpointInterface {
  //   file:File;
  //   name:string;
  //   fileSize:number;
  //   partSize:number;
  //   uploadId:string;
  // };、

  /**
   * 分片续传
   * checkpoint:中断上传的文件
   * progress：进度回调函数
   */
  resume(checkpoint, progress) {
    const { uploadId, file } = checkpoint;
    const { parallel, partSize, path } = this;
    return this.allOSS.multipartUpload(uploadId, file, {
      parallel,
      partSize,
      progress,
      checkpoint,
    });
  }
  //  获取路径
  accessPath(fileName) {
    const { path } = this;
    return path ? `${path}/${fileName}` : fileName;
  }

  //  获取名称
  getFileName(file) {
    let { defaultName } = this;
    const fileName = file.name;
    if (defaultName) return fileName;
    return this.randomFileName();
  }

  //  随机文件名称
  randomFileName() {
    const data = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
    ];
    let nums = "";
    const { length } = this;
    for (let i = 0; i < length; i++) {
      const randomStr = (Math.random() * 61).toString();
      const r = parseInt(randomStr, 10);
      nums += data[r].toString();
    }
    return nums;
  }
}

/*
  example:

  <template>
    <div class="home">
      <input type="file" multiple='true' @change="onFileChange" id="file">
      <el-button @click="upload">普通上传</el-button>
      <el-button @click="multipartUpload">分片上传</el-button>
      <el-button @click="stop">停止上传</el-button>
      <el-button @click="resume">中断续传</el-button>
      <el-progress :percentage="percentage"></el-progress>
    </div>
  </template>

  <script lang="ts">
  import { Component, Vue } from 'vue-property-decorator';
  import AliOss from "ali-oss";

  import DockingOSS from '@/assets/DockingOSS';

  let dockOss = new DockingOSS({
    //  地域节点
    region:"*********",
    //  id
    accessKeyId:"************",
    //  访问密钥
    accessKeySecret:"***********",
    //  bucket
    bucket:"***********",
    path:"***********",
    secure: true
  })

  @Component
  export default class HelloWorld extends Vue {
    //    中断上传存储文件内容
    private checkpoints:object = {};
    private percentage:number = 0;
    private filesArr:File[] = [];

    //  文件更改
    private onFileChange(e:Event):void{
      const target = Reflect.get(e,"target");
      const value = Reflect.get(target,"value");
      const tmpcnt = value.lastIndexOf(".")
      const exname = value.substring(tmpcnt + 1)
      const oFile = document.getElementById("file") || document.createElement("input");
      const files:File[] = Reflect.get(oFile,"files");
      const fileList = Array.from(files);
      this.filesArr = fileList;
    }

    //  分片上传
    private multipartUpload() {
      this.percentage = 0;
      this.filesArr.forEach((file:File) => {
          //  当停止上传时需要也会走向catch
          //  错误提示：{status: 0, name: "cancel"}
          //  需要特殊处理
          dockOss.multipartUpload(file,this.onMultipartUploadProgress)
      });
    }

    //  上传进度
    //  checkpoint：返回的文件对象
    //  如果文件太小，小于分片大小的话，则不会checkpoint，为undefined
    //  说明文件直接上传成功了
    private onMultipartUploadProgress(e:number,checkpoint:any){
      Reflect.set(this.checkpoints,checkpoint.uploadId,checkpoint)
      this.percentage = Number((e * 100).toFixed(0));
      if(e === 1){
        Reflect.deleteProperty(this.checkpoints,checkpoint.uploadId);
      }
    }

    //  普通上传
    private upload():void{
      this.filesArr.forEach((file:File) => {
        dockOss.upload(file);
      })
    }

    //  中止上传
    private stop():void{
      dockOss.cancel()
    }

    //  续传
    private resume():void{
      Object.values(this.checkpoints).forEach((checkpoint) => {
        dockOss.resume(checkpoint,this.onMultipartUploadProgress)
      });
    }

  }
  </script>

*/
